<template>
	<van-from>
	<van-cell-group inset>
		<van-field label="任务总量" v-model="total">
			<template #button>
				<van-button type="primary" @click="defaultDistributeTotal" size="small">自动拆分</van-button>
				<van-button type="success" @click="distributeTotal" size="small"
					style="margin-left: 0.625rem;">手动拆分</van-button>
			</template>
		</van-field>
		<van-field v-for="(task,index) in tasks" :key="index" v-model="task.quantity" :label="task.point" disabled>
			<template #button>
				<van-stepper v-model="task.percentage" :min="0" :max="100" />
			</template>
		</van-field>
	</van-cell-group>
	  <div style="margin: 16px;">
	    <van-button round block type="primary">
	      提交
	    </van-button>
	  </div>
	  </van-from>
</template>

<script setup lang="ts">
	import { ref, reactive,onMounted } from 'vue'
	import { showNotify } from 'vant';
	
	interface Task {
	  point: string;
	  quantity: number;
	  percentage: number;
	}

	const total = ref(0)
	
	const startDate = ref('2024-01-01');
	const endDate = ref('2024-10-01');

	const tasks = reactive<Task[]>([]);
	
    onMounted(() => {
		const months = getMonthRange(startDate.value,endDate.value);
		months.forEach((month) => {
			tasks.push({
			point: month,
			quantity: 0,
			percentage: 0
			})
		})
    });
	
	const getMonthRange = (startDate:string, endDate:string) => {
	    // 创建 Date 对象
	    let start = new Date(startDate);
	    let end = new Date(endDate);
	    // 结果数组
	    let months = [];
	    // 逐月循环
	    while (start <= end) {
	        // 格式化年月
	        let year = start.getFullYear();
	        let month = (start.getMonth() + 1).toString().padStart(2, '0'); // 保证两位数
	        months.push(`${year}-${month}`);
	        
	        // 增加一个月
	        start.setMonth(start.getMonth() + 1);
	    }
	    return months;
	}

	// 计算每个任务的 quantity 和 percentage
	const defaultDistributeTotal = () => {
		const numTasks = tasks.length;
		// 计算每个任务的基础分配量（向下取整）
		const baseQuantity = Math.floor(total.value / numTasks);
		// 计算所有任务分配后的总数量
		let allocatedQuantity = baseQuantity * numTasks;
		// 计算剩余的部分
		const remainder = total.value - allocatedQuantity;
		// 分配 quantity
		tasks.forEach((task, index) => {
			task.quantity = baseQuantity;
			// 将余数分配到最后一个任务
			if (index == numTasks - 1) {
				task.quantity += remainder;
			}
		});
		// 计算每个任务的百分比（保留整数部分）
		tasks.forEach((task) => {
			task.percentage = Math.floor((task.quantity / total.value) * 100);
		});
		// 确保百分比总和为 100，可能需要将余数调整到最后一个任务
		const totalPercentage = tasks.reduce((sum, task) => sum + task.percentage, 0);
		const percentageRemainder = 100 - totalPercentage;
		// 将百分比余数加到最后一个任务
		tasks[tasks.length - 1].percentage += percentageRemainder;
	};

	// 计算任务数量
	const distributeTotal = () => {
		clearQuantity();
		const nonZeroTasks = tasks.filter(task => task.percentage > 0); // 过滤掉百分比为0的任务
		const nonZeroPercentage = nonZeroTasks.reduce((sum, task) => sum + task.percentage, 0);

		// 1. 确保总的百分比为100%
		if (tasks.reduce((sum, task) => sum + task.percentage, 0) != 100) {
			showNotify('百分比总和必须为100%');
			return;
		}

		// 2. 计算任务的数量分配
		let totalAssigned = 0;  // 已分配的数量

		// 归一化剩余百分比（不包含百分比为0的任务）
		nonZeroTasks.forEach(task => {
			const normalizedPercentage = (task.percentage / nonZeroPercentage) * 100;  // 归一化
			const calculatedQuantity = Math.floor((normalizedPercentage / 100) * total.value);
			task.quantity = calculatedQuantity;
			totalAssigned += task.quantity;
		});

		// 3. 处理余数：将剩余的数量分配给最后一个任务
		let remainder = total.value - totalAssigned;
		if (remainder != 0) {
			const lastNonZeroTask = nonZeroTasks[nonZeroTasks.length - 1];
			lastNonZeroTask.quantity += remainder;  // 将余数加到最后一个任务
		}

		// 4. 更新百分比：基于新的数量更新百分比
		tasks.forEach(task => {
			if (task.percentage > 0) {
				task.percentage = Math.round((task.quantity / total.value) * 100);
			}
		});

		// 5. 确保任务总量与百分比匹配
		const totalQuantity = tasks.reduce((sum, task) => sum + task.quantity, 0);
		if (totalQuantity != total.value) {
			console.warn("分配后的任务数量总和与总量不符！");
		}
	};
	
	const clearQuantity = ()=>{
		tasks.forEach((task) => {
			task.quantity = 0;
		});
	}
	
</script>

<style>
</style>